package st.business.tepth.business.user.busnumber.workholder.repair.work.content;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import st.business.tepth.base.OnDataConvertListener;
import st.business.tepth.business.bean.PartLocationBean;
import st.business.tepth.business.bean.PickGoodsWrapper;
import st.business.tepth.business.bean.PostDiagnoseWrapperBean;
import st.business.tepth.business.bean.RepairTaskTypeBean;
import st.business.tepth.config.Url;
import st.shadow.library.core.net.callback.IError;
import st.shadow.library.core.net.callback.ISuccess;
import st.shadow.library.core.net.data.ObjConverter;
import st.shadow.library.core.net.rx.RxRestClient;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-01-14 19:23
 */

public class RepairModel implements RepairContract.Model {


    @Override
    public Disposable getWorkData(String token, int repairId,
                                  int vehicleSeriesId,
                                  final OnDataConvertListener<RepairTaskTypeBean> listener) {
        return RxRestClient.builder()
                .url(Url.GetMyRepairTask)
                .params("repairId", repairId)
                .params("token", token)
                .params("vehicleSeriesId", vehicleSeriesId)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        listener.convert(convertToBusRepairInfo(response));
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                    }
                })
                .build()
                .get();
    }

    @Override
    public Disposable postDiagnoseList(final String token, final int repairId,
                                       final int repairTaskId,
                                       final int vehicleSeriesId,
                                       String faultDiagnosticList,
                                       final OnDataConvertListener<PostDiagnoseWrapperBean> listener) {
        return RxRestClient.builder()
                .url(Url.ConfirmDiagnose)
                .params("repairId", repairId)
                .params("token", token)
                .params("repairTaskId", repairTaskId)
                .params("faultDiagnosticList", faultDiagnosticList)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        listener.convert(convertDiagnoseList(response));
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        listener.error(code, msg);
                    }
                })
                .build()
                .post();

    }

    @Override
    public Disposable postProgram(final String token, final int repairId,
                                  final int repairTaskId,
                                  final int vehicleSeriesId, String taskItemList,
                                  final OnDataConvertListener<PickGoodsWrapper>
                                          pickListener,
                                  final OnDataConvertListener<RepairTaskTypeBean> listener) {
        return RxRestClient.builder()
                .url(Url.ConfirmProgram)
                .params("token", token)
                .params("repairTaskId", repairTaskId)
                .params("taskItemList", taskItemList)
                .build()
                .flatPost()
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap(new Function<String, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(String response) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
//                            String object = jsonObject.getString("data");
//                            if (pickListener != null) {
//                                pickListener.convert(convertToPickGoods(object));
//                            }
                            if (pickListener != null) {
                                pickListener.convert(null);
                            }
                            return RxRestClient.builder()
                                    .url(Url.GetMyRepairTask)
                                    .params("repairId", repairId)
                                    .params("token", token)
                                    .params("vehicleSeriesId", vehicleSeriesId)
                                    .build()
                                    .onlyPost();
                        } else {
                            return Observable.error(new Throwable(ResultMsg));
                        }

                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<String>() {

                    @Override
                    public void onNext(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String object = jsonObject.getString("data");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            listener.convert(convertToBusRepairInfo(object));
                        } else {
                            listener.error(ResultCode, ResultMsg);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        listener.error(-1, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public Disposable deleteDiagnose(final String token, final int repairId,
                                     final int vehicleSeriesId,
                                     int faultDiagnosticId, int faultDiagnosticIdType,
                                     final OnDataConvertListener<String> deleteListener,
                                     final OnDataConvertListener<RepairTaskTypeBean> listener) {
        return RxRestClient.builder()
                .url(Url.DeleteDiagnostic)
                .params("repairId", repairId)
                .params("token", token)
                .params("faultDiagnosticId", faultDiagnosticId)
                .params("faultDiagnosticIdType", faultDiagnosticIdType)
                .build()
                .flatPost()
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap(new Function<String, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(String response) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            if (deleteListener != null) {
                                deleteListener.convert("");
                            }
                            return RxRestClient.builder()
                                    .url(Url.GetMyRepairTask)
                                    .params("repairId", repairId)
                                    .params("token", token)
                                    .params("vehicleSeriesId", vehicleSeriesId)
                                    .build()
                                    .onlyPost();
                        } else {
                            return Observable.error(new Throwable(ResultMsg));
                        }

                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<String>() {

                    @Override
                    public void onNext(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            String object = jsonObject.getString("data");
                            listener.convert(convertToBusRepairInfo(object));
                        } else {
                            listener.error(ResultCode, ResultMsg);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        listener.error(-1, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public Disposable deleteProgram(String token, int repairId,
                                    int faultDiagnosticId, int planId,
                                    final OnDataConvertListener<String> listener) {
        return RxRestClient.builder()
                .url(Url.DeleteProgram)
                .params("repairId", repairId)
                .params("token", token)
                .params("diagnosticId", faultDiagnosticId)
                .params("planId", planId)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        listener.convert(response);
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        listener.error(code, msg);
                    }
                })
                .build()
                .post();
    }

    @Override
    public Disposable submitFinishWork(final String token,
                                       final int repairId,
                                       final int repairTaskId,
                                       final int vehicleSeriesId,
                                       final OnDataConvertListener<RepairTaskTypeBean>
                                               dataListener,
                                       final OnDataConvertListener<String>
                                               statusListener) {
        return RxRestClient.builder()
                .url(Url.SubmitFinishWork)
                .params("token", token)
                .params("repairTaskId", repairTaskId)
                .build()
                .flatPost()
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap(new Function<String, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(String response) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            String object = jsonObject.getString("data");
                            JSONObject jsonResult = JSONObject.parseObject(object);
                            int status = jsonResult.getInteger("repairStatus");
                            if (status < 4) {
                                return RxRestClient.builder()
                                        .url(Url.GetMyRepairTask)
                                        .params("repairId", repairId)
                                        .params("token", token)
                                        .params("vehicleSeriesId", vehicleSeriesId)
                                        .build()
                                        .onlyPost();
                            } else {
                                return Observable.error(new MyThrowable());
                            }
                        } else {
                            return Observable.error(new Throwable(ResultMsg));
                        }
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<String>() {

                    @Override
                    public void onNext(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String object = jsonObject.getString("data");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            dataListener.convert(convertToBusRepairInfo(object));
                        } else {
                            dataListener.error(ResultCode, ResultMsg);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof MyThrowable) {
                            statusListener.convert("");
                        } else {
                            dataListener.error(-1, e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public Disposable pickGoods(final String token,
                                final int repairId,
                                final int vehicleSeriesId,
                                String materialApplyList,
                                final OnDataConvertListener<String> pickListener,
                                final OnDataConvertListener<RepairTaskTypeBean> listener) {
        return RxRestClient.builder()
                .url(Url.PickGoods)
                .params("token", token)
                .params("items", materialApplyList)
                .build()
                .flatPost()
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap(new Function<String, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(String response) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            if (pickListener != null) {
                                pickListener.convert(ResultMsg);
                            }
                            return RxRestClient.builder()
                                    .url(Url.GetMyRepairTask)
                                    .params("repairId", repairId)
                                    .params("token", token)
                                    .params("vehicleSeriesId", vehicleSeriesId)
                                    .build()
                                    .onlyPost();
                        } else {
                            return Observable.error(new Throwable(ResultMsg));
                        }
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<String>() {

                    @Override
                    public void onNext(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String object = jsonObject.getString("data");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            listener.convert(convertToBusRepairInfo(object));
                        } else {
                            listener.error(ResultCode, ResultMsg);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof MyThrowable) {
                            pickListener.convert("");
                        } else {
                            listener.error(-1, e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public Disposable returnGoods(final String token, String items, int planId,
                                  final OnDataConvertListener<String> returnListener) {
        return RxRestClient.builder()
                .url(Url.MaterialReturn)
                .params("token", token)
                .params("planId", planId)
                .params("items", items)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        returnListener.convert(response);
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        returnListener.error(code, msg);
                    }
                })
                .build()
                .post();
    }

    @Override
    public Disposable addCoWorker(String token, int id, final OnDataConvertListener<String> listener) {
        return RxRestClient.builder()
                .url(Url.AddCoWorker)
                .params("token", token)
                .params("sceneRepairPlanId", id)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        listener.convert(response);
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        listener.error(code, msg);
                    }
                })
                .build()
                .post();
    }

    @Override
    public Disposable cancelCoWorker(String token, int id, final OnDataConvertListener<String> listener) {
        return RxRestClient.builder()
                .url(Url.CancelCoWorker)
                .params("token", token)
                .params("sceneRepairPlanId", id)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        listener.convert(response);
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        listener.error(code, msg);
                    }
                })
                .build()
                .post();
    }

    @Override
    public Disposable cancelFinishWork(final String token, final int repairId,
                                       int repairTaskId,
                                       final int vehicleSeriesId,
                                       final OnDataConvertListener<String> cancelListener,
                                       final OnDataConvertListener<RepairTaskTypeBean> dataListener) {
        return RxRestClient.builder()
                .url(Url.CancelFinishWork)
                .params("repairId", repairId)
                .params("token", token)
                .params("repairTaskId", repairTaskId)
                .build()
                .flatPost()
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap(new Function<String, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(String response) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            if (cancelListener != null) {
                                cancelListener.convert("");
                            }
                            return RxRestClient.builder()
                                    .url(Url.GetMyRepairTask)
                                    .params("repairId", repairId)
                                    .params("token", token)
                                    .params("vehicleSeriesId", vehicleSeriesId)
                                    .build()
                                    .onlyPost();
                        } else {
                            return Observable.error(new Throwable(ResultMsg));
                        }
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<String>() {

                    @Override
                    public void onNext(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String object = jsonObject.getString("data");
                        String ResultMsg = jsonObject.getString("msg");
                        if (0 == ResultCode) {
                            dataListener.convert(convertToBusRepairInfo(object));
                        } else {
                            cancelListener.error(ResultCode, ResultMsg);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        cancelListener.error(-1, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    @Override
    public Disposable addTempLocation(String token, String tempLocation, final OnDataConvertListener<List<PartLocationBean>> listener) {
        return RxRestClient.builder()
                .url(Url.AddTempLocation)
                .params("token", token)
                .params("positionList", tempLocation)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        listener.convert(convertPartLocation(response));
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        listener.error(code, msg);
                    }
                })
                .build()
                .post();
    }
    private RepairTaskTypeBean convertToBusRepairInfo(String response) {
        return new ObjConverter<RepairTaskTypeBean>().convert(response
                , new TypeReference<RepairTaskTypeBean>() {
                });
    }

    private PostDiagnoseWrapperBean convertDiagnoseList(String response) {
        return new ObjConverter<PostDiagnoseWrapperBean>().convert(response
                , new TypeReference<PostDiagnoseWrapperBean>() {
                });
    }

    private PickGoodsWrapper convertToPickGoods(String response) {
        return new ObjConverter<PickGoodsWrapper>().convert(response
                , new TypeReference<PickGoodsWrapper>() {
                });
    }
    private List<PartLocationBean> convertPartLocation(String response) {
        return new ObjConverter<List<PartLocationBean>>().convert(response
                , new TypeReference<List<PartLocationBean>>() {
                });
    }
    private class MyThrowable extends Throwable {

    }
}
